#include "T_CaseInformation.h"
#include "ElaText.h"
#include "ElaPushButton.h"
#include "ElaCheckBox.h"
#include "ElaScrollPageArea.h"
#include "ElaWidget.h"
#include "ElaTheme.h"
#include "ElaToolButton.h"
#include "ElaLCDNumber.h"
//#include "ElaToggleSwitch.h"
#include "T_Widget.h"
#include <QDateTime>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFile>
#include <QLabel>
#include <QDebug>

#include <QFileDialog>
#include <QStandardPaths>
#include "ElaMessageBar.h"

T_CaseInformation::T_CaseInformation(QWidget *parent):T_BasePage(parent) {
    setTitleVisible(false);
    connect(eTheme,&ElaTheme::themeModeChanged,this,[=](){
        qDebug()<<"ThemeMode has been changed!";
        if(cardinformationColor == 0)
            cardinformationColor = 1;
        else
            cardinformationColor = 0;
        if(cardinformationColor == 0)
        {
            for(int i =0;i<cardNumber;i++)
            {
                cardVector.at(i)->_content->setStyleSheet("background:#3A3A3A");
            }
        }
        else
        {
            for(int i =0;i<cardNumber;i++)
            {
                cardVector.at(i)->_content->setStyleSheet("background:white");
            }
        }
    });
    T_Widget *w = new T_Widget();
    _lcdNumber = new ElaLCDNumber(this);
    _lcdNumber->setIsUseAutoClock(true);
    _lcdNumber->setIsTransparent(false);
    //_lcdNumber->setAutoClockFormat("hh:mm:ss");
    _lcdNumber->setFixedHeight(100);


    ElaScrollPageArea *infromationArea = new ElaScrollPageArea(this);
    infromationArea->setFixedSize(340,650);
    QVBoxLayout *informationLayout = new QVBoxLayout(infromationArea);
    QHBoxLayout *baseinformationLayout = new QHBoxLayout();
    QHBoxLayout *picLayout = new QHBoxLayout();
    ElaText *baseInformationTitle = new ElaText("患者基本信息",this);
    baseInformationTitle->setTextStyle(ElaTextType::TextStyle::Title);
    ElaToolButton *selectBtn = new ElaToolButton();
    connect(selectBtn,&ElaToolButton::clicked,this,[=]{});
    //selectBtn->setFixedSize(41,41);
    //QPixmap pixmap(":/resource/Image/Cirno-Small.jpg");
    selectBtn->setElaIcon(ElaIconType::AddressCard);
    //selectBtn->setIconSize(QSize(41, 41));
    baseinformationLayout->addStretch();
    baseinformationLayout->addWidget(baseInformationTitle);
    baseinformationLayout->addWidget(selectBtn);
    baseinformationLayout->setContentsMargins(0,0,0,0);
    baseinformationLayout->addStretch();

    QLabel *pic = new QLabel(this);
    pic->setFixedSize(100,125);

    ElaText *name = new ElaText("姓名：",this);
    ElaText *gender = new ElaText("性别：",this);
    ElaText *age = new ElaText("年龄：",this);
    ElaText *zone = new ElaText("病区：",this);
    ElaText *Id = new ElaText("患者ID：",this);

    name->setTextStyle(ElaTextType::TextStyle::Body);
    gender->setTextStyle(ElaTextType::TextStyle::Body);
    age->setTextStyle(ElaTextType::TextStyle::Body);
    zone->setTextStyle(ElaTextType::TextStyle::Body);
    Id->setTextStyle(ElaTextType::TextStyle::Body);

    QHBoxLayout *firstLayout = new QHBoxLayout();
    firstLayout->setContentsMargins(0,0,0,0);
    firstLayout->addWidget(name);
    firstLayout->addWidget(age);
    firstLayout->addWidget(gender);

    QHBoxLayout *secondLayout = new QHBoxLayout();
    secondLayout->setContentsMargins(0,0,0,0);
    secondLayout->addWidget(zone);

    QHBoxLayout *thirdLayout = new QHBoxLayout();
    thirdLayout->setContentsMargins(0,0,0,0);
    thirdLayout->addWidget(Id);

    QVBoxLayout *totalLayout = new QVBoxLayout();
    totalLayout->setContentsMargins(0,0,0,0);
    totalLayout->addLayout(firstLayout);
    totalLayout->addLayout(secondLayout);
    totalLayout->addLayout(thirdLayout);

    picLayout->addWidget(pic);
    //picLayout->addSpacing(-70);
    picLayout->addLayout(totalLayout);
    //picLayout->setContentsMargins(0,0,0,0);

    /*QHBoxLayout *baseLayout = new QHBoxLayout();
    baseLayout->setContentsMargins(0,0,0,0);
    baseLayout->addLayout(picLayout);
    baseLayout->addLayout(totalLayout);*/


    QHBoxLayout *lineLayout = new QHBoxLayout();
    lineLayout->addWidget(new QLabel("")); // 左侧占位


    QFrame *line = new QFrame();
    line->setFrameShape(QFrame::HLine); // 设置为水平线
    line->setFrameShadow(QFrame::Sunken); // 设置线条样式
    line->setFixedWidth(250);
    lineLayout->addWidget(line);
    lineLayout->addWidget(new QLabel("")); // 右侧占位


    dateTag->setIsWrapAnywhere(true);
    dateTag->setTextStyle(ElaTextType::TextStyle::Body);
    diagnosisTag->setIsWrapAnywhere(true);
    diagnosisTag->setTextStyle(ElaTextType::TextStyle::Body);
    bodycheckTag->setIsWrapAnywhere(true);
    bodycheckTag->setTextStyle(ElaTextType::TextStyle::Body);
    complaintTag->setIsWrapAnywhere(true);
    complaintTag->setTextStyle(ElaTextType::TextStyle::Body);
    presenthistoryTag->setIsWrapAnywhere(true);
    presenthistoryTag->setTextStyle(ElaTextType::TextStyle::Body);
    anamnesisTag->setIsWrapAnywhere(true);
    anamnesisTag->setTextStyle(ElaTextType::TextStyle::Body);

    QVBoxLayout *detailLayout = new QVBoxLayout();
    detailLayout->addWidget(dateTag);
    detailLayout->addWidget(dateEdit);
    dateEdit->setMinimumHeight(30);
    detailLayout->addWidget(diagnosisTag);
    detailLayout->addWidget(diagnosisEdit);
    diagnosisEdit->setMinimumHeight(30);
    detailLayout->addWidget(bodycheckTag);
    detailLayout->addWidget(bodycheckEdit);
    bodycheckEdit->setMinimumHeight(60);
    detailLayout->addWidget(complaintTag);
    detailLayout->addWidget(complaintEdit);
    complaintEdit->setMinimumHeight(60);
    detailLayout->addWidget(presenthistoryTag);
    detailLayout->addWidget(presenthistoryEdit);
    presenthistoryEdit->setMinimumHeight(60);
    detailLayout->addWidget(anamnesisTag);
    detailLayout->addWidget(anamnesisEdit);
    anamnesisEdit->setMinimumHeight(60);

    QHBoxLayout *checkboxLayout = new QHBoxLayout();
    ElaCheckBox *enableEdit = new ElaCheckBox(this);
    enableEdit->setEnabled(false);
    ElaText *checkTitle = new ElaText("开启编辑");
    checkTitle->setTextStyle(ElaTextType::TextStyle::Subtitle);
    checkboxLayout->addStretch();
    checkboxLayout->addWidget(checkTitle);
    checkboxLayout->addWidget(enableEdit);
    checkboxLayout->addStretch();


    informationLayout->addLayout(baseinformationLayout);
    /*informationLayout->addLayout(firstLayout);
    informationLayout->addLayout(secondLayout);*/
    informationLayout->addLayout(picLayout);
    informationLayout->addLayout(lineLayout);
    informationLayout->addLayout(detailLayout);
    informationLayout->addLayout(checkboxLayout);
    informationLayout->addStretch();


    ElaScrollPageArea *logArea = new ElaScrollPageArea(this);
    logArea->setFixedSize(340,650);
    QVBoxLayout *logLayout = new QVBoxLayout(logArea);

    ElaText *logTitle = new ElaText("患者病案日志");
    logTitle->setTextStyle(ElaTextType::TextStyle::Title);
    QHBoxLayout *logtitleLayout = new QHBoxLayout();
    logtitleLayout->addStretch();
    logtitleLayout->addWidget(logTitle);
    logtitleLayout->addStretch();

    ElaText *logSubtitle = new ElaText("病房主要活动情况");
    logSubtitle->setTextStyle(ElaTextType::TextStyle::Subtitle);
    QHBoxLayout *logsubtitleLayout = new QHBoxLayout();
    logsubtitleLayout->addStretch();
    logsubtitleLayout->addWidget(logSubtitle);
    logsubtitleLayout->addStretch();

    /*ExpandableCard *card0 = new ExpandableCard("五病区7好病房","10:00-12:00","病人正常服药");
    ExpandableCard *card1 = new ExpandableCard("五病区7好病房","10:00-12:00","病人正常服药");
    ExpandableCard *card2 = new ExpandableCard("五病区7好病房","10:00-12:00","病人正常服药");
    ExpandableCard *card3 = new ExpandableCard("五病区7好病房","10:00-12:00","病人正常服药");
    ExpandableCard *card4 = new ExpandableCard("五病区7好病房","10:00-12:00","病人正常服药");
    ExpandableCard *card5 = new ExpandableCard("五病区7好病房","10:00-12:00","病人正常服药");
    ExpandableCard *card6 = new ExpandableCard("五病区7好病房","10:00-12:00","病人正常服药丹凤街短时间内反抗精神的放开你的手九年"
                                                                               "第三方的世界妇女四道口附近空手道解放你"
                                                                               "独守空房数据库的方式打击开发商的接口"
                                                                               "但凡是看到开发商的恐惧愤怒恐惧上的那颗"
                                                                               "但凡扣税的女粉丝大家看法可减少对健康");*/
    QVBoxLayout *cardLayout = new QVBoxLayout();
    ElaPushButton *addBtn = new ElaPushButton(this);
    addBtn->setText("添加日志");
    addBtn->setEnabled(false);

    QHBoxLayout *cardcheckLayout = new QHBoxLayout();
    ElaCheckBox *editCard = new ElaCheckBox(this);
    editCard->setEnabled(false);
    ElaText *editcardText = new ElaText("编辑日志",this);
    editcardText->setTextStyle(ElaTextType::TextStyle::Subtitle);
    cardcheckLayout->addStretch();
    cardcheckLayout->addWidget(editcardText);
    cardcheckLayout->addWidget(editCard);
    cardcheckLayout->addStretch();

    connect(editCard,&ElaCheckBox::stateChanged,this,[=](){
        bool isChecked = editCard->isChecked();

        qDebug() << "patient event card state changed: " << isChecked;

        if(isChecked)
        {
            addBtn->setEnabled(true);
            int num = 0;
            num = cardVector.size();
            qDebug()<<num;
            for(int i=0;i<num;i++)
            {
                cardVector.at(i)->signaleditEnable();
            }
        }
        else
        {
            addBtn->setEnabled(false);
            int num = 0;
            num = cardVector.size();
            for(int j=0;j<num;j++)
            {
                cardVector.at(j)->signaleditDisable();
            }

            QString getName = name->text();
            QString getZone = zone->text();
            QString getAge = age->text();
            QString getId = Id->text();
            QString getGender = gender->text();

            QString getDate = dateTag->text();
            QString getDiagnosis = diagnosisTag->text();
            QString getBodycheck = bodycheckTag->text();
            QString getComplaint = complaintTag->text();
            QString getPresent = presenthistoryTag->text();
            QString getAnamnesis = anamnesisTag->text();

            QFile file(w->fileName);
            file.open(QIODevice::WriteOnly | QIODevice::Text);
            QTextStream out(&file);

            QString infileName = getName.mid(3);
            QString infileAge = getAge.mid(3);
            QString infileGender = getGender.mid(3);
            QString infileZone = getZone.mid(3);
            QString infileId = getId.mid(5);

            QString infileDate = getDate.mid(5);
            QString infileDiagnosis = getDiagnosis.mid(5);
            QString infileBodycheck = getBodycheck.mid(5);
            QString infileComplaint = getComplaint.mid(3);
            QString infilePresent = getPresent.mid(4);
            //qDebug()<<infilePresent;
            QString infileAnamnesis = getAnamnesis.mid(4);


            _name = getName.mid(3);
            _age = getAge.mid(3);
            _gender = getGender.mid(3);
            _zone = getZone.mid(3);
            _Id = getId.mid(5);

            _date = getDate.mid(5);
            _diagnosis = getDiagnosis.mid(5);
            _bodycheck = getBodycheck.mid(5);
            _complaint = getComplaint.mid(3);
            _presenthistory = getPresent.mid(4);
            _anamnesis = getAnamnesis.mid(4);

            out<<"[name]\n";
            out<<infileName+'\n';
            out<<"[gender]\n";
            out<<infileGender+'\n';
            out<<"[age]\n";
            out<<infileAge+'\n';
            out<<"[zone]\n";
            out<<infileZone+'\n';
            out<<"[Id]\n";
            out<<infileId+'\n';
            out<<"[date]\n";
            out<<infileDate+'\n';
            out<<"[diagnosis]\n";
            out<<infileDiagnosis+'\n';
            out<<"[bodycheck]\n";
            out<<infileBodycheck+'\n';
            out<<"[complaint]\n";
            out<<infileComplaint+'\n';
            out<<"[presenthistory]\n";
            out<<infilePresent+'\n';
            out<<"[anamnesis]\n";
            out<<infileAnamnesis+'\n';
            out<<"[time]\n";

            for(int i=0;i<cardNumber;i++)
            {
                QString time =  cardVector.at(i)->timeLabel->text();
                _timeVec.push_back(time);
                out<<time+'\n';
            }
            out<<"[manner]\n";
            for(int i=0;i<cardNumber;i++)
            {
                QString content =  cardVector.at(i)->analysisLabel->text();
                _contentVec.push_back(content);
                out<<content+'\n';
            }

            out<<"[notes]\n";
            out<< w->_notes+'\n';
        }
    });

    cardLayout->addWidget(addBtn);
    cardLayout->addLayout(cardcheckLayout);
    /*cardLayout->addWidget(card0);
    cardLayout->addWidget(card1);
    cardLayout->addWidget(card2);
    cardLayout->addWidget(card3);
    cardLayout->addWidget(card4);
    cardLayout->addWidget(card5);
    cardLayout->addWidget(card6);*/

    logLayout->addLayout(logtitleLayout);
    logLayout->addLayout(logsubtitleLayout);
    logLayout->addLayout(cardLayout);
    logLayout->addStretch(); 
    /*ElaScrollPageArea *analyisArea = new ElaScrollPageArea(this);
    analyisArea->setFixedSize(300,800);
    QVBoxLayout *analyisLayout = new QVBoxLayout(analyisArea);
    ElaPushButton *analyisBtn = new ElaPushButton("test01",analyisArea);
    analyisLayout->addWidget(analyisBtn);
    analyisLayout->addStretch();*/
    QHBoxLayout *contentLayout = new QHBoxLayout();
    contentLayout->addWidget(infromationArea);
    contentLayout->addWidget(logArea);
    connect(selectBtn,&ElaToolButton::clicked,this,[=](){
        w->show();
    });

    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *centralLayout = new QVBoxLayout(centralWidget);
    centralLayout->addWidget(_lcdNumber);





    ElaPushButton *btnImport = new ElaPushButton("导入病例",this);
    connect(btnImport, &ElaPushButton::clicked, this, &T_CaseInformation::onImportClicked);

    // 添加保存按钮布局
    QHBoxLayout* btnControlLayout = new QHBoxLayout();
    ElaPushButton *btnSave = new ElaPushButton("保存病历", this);
    // 将按钮加入布局
    btnControlLayout->addStretch();
    btnControlLayout->addWidget(btnSave);
    btnControlLayout->addWidget(btnImport);
    btnControlLayout->addStretch();

    // 将按钮布局添加到主布局
    centralLayout->addLayout(btnControlLayout); // 添加到主布局末尾

    connect(btnSave, &ElaPushButton::clicked, this, &T_CaseInformation::onSaveClicked);






    centralLayout->addLayout(contentLayout);
    //centralLayout->addWidget(infromationArea);
    //centralLayout->addWidget(logArea);
    //centralLayout->addWidget(analyisArea);
    centralLayout->addStretch();
    centralLayout->setContentsMargins(0, 0, 0, 0);

    addCentralWidget(centralWidget,true,true,0);
    connect(w,&T_Widget::isSelected,this,[=](){
        qDebug()<<"selected is running!";

        infromationArea->setFixedSize(340,650);
        logArea->setFixedSize(340,650);

        QPixmap pixmap = QPixmap::fromImage(w->image);
        QPixmap scaledPixmap = pixmap.scaled(
            pic->size(),
            Qt::KeepAspectRatio,
            Qt::SmoothTransformation  // 平滑缩放
            );
        pic->setPixmap(scaledPixmap);

        if(!cardVector.isEmpty())
        {
            for(int i =0;i<cardNumber;i++)
            {
                cardLayout->removeWidget(cardVector.at(i));
                cardVector.at(i)->setParent(nullptr);
                delete cardVector.at(i);
            }
            cardVector.clear();
        }


        _name = w->_name;
        _age = w->_age;
        _gender = w->_gender;
        _zone = w->_zone;
        _Id = w->_Id;

        _date = w->_date;
        _diagnosis = w->_diagnosis;
        _bodycheck = w->_bodycheck;
        _complaint = w->_complaint;
        _presenthistory = w->_presenthistory;
        _anamnesis = w->_anamnesis;
        _timeVec = w->timeVec;
        _contentVec = w->contentVec;


        QString str;
        str = "姓名:"+w->_name;
        name->setText(str);
        str = "性别:"+w->_gender;
        gender->setText(str);
        str = "年龄:"+w->_age;
        age->setText(str);
        str = "患者ID:"+w->_Id;
        Id->setText(str);
        str = "病区:"+w->_zone;
        zone->setText(str);
        str = "入院日期:"+w->_date;
        dateTag->setText(str);
        str = "入院诊断:"+w->_diagnosis;
        diagnosisTag->setText(str);
        str = "入院查体:"+w->_bodycheck;
        bodycheckTag->setText(str);
        str = "主诉:"+w->_complaint;
        complaintTag->setText(str);
        str = "现病史:"+w->_presenthistory;
        presenthistoryTag->setText(str);
        str = "既往史:"+w->_anamnesis;
        anamnesisTag->setText(str);
        cardNumber = w->timeVec.count();
        for(int i = 0; i < cardNumber; i++)
        {
            ExpandableCard *card = new ExpandableCard(w->timeVec.at(i),w->_zone,w->contentVec.at(i), this);
            cardVector.push_back(card);
            qDebug()<<cardVector.size();
            cardLayout->insertWidget(i,card);
        }
        editCard->setEnabled(true);
        enableEdit->setEnabled(true);
    });
    dateEdit->hide();
    diagnosisEdit->hide();
    bodycheckEdit->hide();
    complaintEdit->hide();
    presenthistoryEdit->hide();
    anamnesisEdit->hide();


    connect(enableEdit,&ElaCheckBox::stateChanged,this,[=](){
        bool isChecked = enableEdit->isChecked();
        if(isChecked)
        {
            // 双击 QLabel 时进入编辑模式
            dateTag->setMouseTracking(true);
            dateTag->installEventFilter(this);

            diagnosisTag->setMouseTracking(true);
            diagnosisTag->installEventFilter(this);

            bodycheckTag->setMouseTracking(true);
            bodycheckTag->installEventFilter(this);

            complaintTag->setMouseTracking(true);
            complaintTag->installEventFilter(this);

            presenthistoryTag->setMouseTracking(true);
            presenthistoryTag->installEventFilter(this);

            anamnesisTag->setMouseTracking(true);
            anamnesisTag->installEventFilter(this);
        }
        else
        {
            dateTag->setMouseTracking(false);
            dateTag->removeEventFilter(this);

            diagnosisTag->setMouseTracking(false);
            diagnosisTag->removeEventFilter(this);

            bodycheckTag->setMouseTracking(false);
            bodycheckTag->removeEventFilter(this);

            complaintTag->setMouseTracking(false);
            complaintTag->removeEventFilter(this);

            presenthistoryTag->setMouseTracking(false);
            presenthistoryTag->removeEventFilter(this);

            anamnesisTag->setMouseTracking(false);
            anamnesisTag->removeEventFilter(this);

            QString getName = name->text();
            QString getZone = zone->text();
            QString getAge = age->text();
            QString getId = Id->text();
            QString getGender = gender->text();

            QString getDate = dateTag->text();
            QString getDiagnosis = diagnosisTag->text();
            QString getBodycheck = bodycheckTag->text();
            QString getComplaint = complaintTag->text();
            QString getPresent = presenthistoryTag->text();
            QString getAnamnesis = anamnesisTag->text();

            QFile file(w->fileName);
            file.open(QIODevice::WriteOnly | QIODevice::Text);
            QTextStream out(&file);

            QString infileName = getName.mid(3);
            QString infileAge = getAge.mid(3);
            QString infileGender = getGender.mid(3);
            QString infileZone = getZone.mid(3);
            QString infileId = getId.mid(5);

            QString infileDate = getDate.mid(5);
            QString infileDiagnosis = getDiagnosis.mid(5);
            QString infileBodycheck = getBodycheck.mid(5);
            QString infileComplaint = getComplaint.mid(3);
            QString infilePresent = getPresent.mid(4);
            QString infileAnamnesis = getAnamnesis.mid(4);

            _name = getName.mid(3);
            _age = getAge.mid(3);
            _gender = getGender.mid(3);
            _zone = getZone.mid(3);
            _Id = getId.mid(5);

            _date = getDate.mid(5);
            _diagnosis = getDiagnosis.mid(5);
            _bodycheck = getBodycheck.mid(5);
            _complaint = getComplaint.mid(3);
            _presenthistory = getPresent.mid(4);
            _anamnesis = getAnamnesis.mid(4);

            out<<"[name]\n";
            out<<infileName+'\n';
            out<<"[gender]\n";
            out<<infileGender+'\n';
            out<<"[age]\n";
            out<<infileAge+'\n';
            out<<"[zone]\n";
            out<<infileZone+'\n';
            out<<"[Id]\n";
            out<<infileId+'\n';
            out<<"[date]\n";
            out<<infileDate+'\n';
            out<<"[diagnosis]\n";
            out<<infileDiagnosis+'\n';
            out<<"[bodycheck]\n";
            out<<infileBodycheck+'\n';
            out<<"[complaint]\n";
            out<<infileComplaint+'\n';
            out<<"[presenthistory]\n";
            out<<infilePresent+'\n';
            out<<"[anamnesis]\n";
            out<<infileAnamnesis+'\n';
            out<<"[time]\n";

            for(int i=0;i<cardNumber;i++)
            {
                QString time =  cardVector.at(i)->timeLabel->text();
                out<<time+'\n';
            }
            out<<"[manner]\n";
            for(int i=0;i<cardNumber;i++)
            {
                QString content =  cardVector.at(i)->analysisLabel->text();
                out<<content+'\n';
            }

            out<<"[notes]\n";
            out<< w->_notes+'\n';
        }
    });


    // 按下回车键或失去焦点时完成编辑,Qlineedit信号是editingFinished.
    connect(dateEdit, &QLineEdit::editingFinished, this, &T_CaseInformation::datefinishEditing);
    connect(diagnosisEdit, &QLineEdit::editingFinished, this, &T_CaseInformation::diagnosisfinishEditing);
    connect(bodycheckEdit, &QLineEdit::editingFinished, this, &T_CaseInformation::bodycheckfinishEditing);
    connect(complaintEdit, &QLineEdit::editingFinished, this, &T_CaseInformation::complaintfinishEditing);
    connect(presenthistoryEdit, &QLineEdit::editingFinished, this, &T_CaseInformation::presenthistoryfinishEditing);
    connect(anamnesisEdit, &QLineEdit::editingFinished, this, &T_CaseInformation::anamnesisfinishEditing);

    connect(addBtn,&ElaPushButton::clicked,[=](){
        QDateTime currentDateTime = QDateTime::currentDateTime();
        QString formattedDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
        ExpandableCard *newCard= new ExpandableCard(formattedDateTime,w->_zone,"", this);
         cardLayout->insertWidget(cardNumber,newCard);
        newCard->contentEdit->setText("请输入日志内容");
        newCard->contentEdit->show();
        newCard->timeLabel->hide();
        newCard->contentEdit->setFocus();
         int Check = editCard->isChecked();
        if(Check) {
            // emit newCard->signaleditEnable();
            // newCard->editEnable();
        } else {
            // emit newCard->signaleditDisable();
            // newCard->editEnable();
            // newCard->editDisable();
        }
         cardVector.push_back(newCard);
         cardNumber++;
         if(cardNumber>=6)
         {
             int height = 650+(cardNumber-5)*80;
             infromationArea->setFixedSize(340,height);
             logArea->setFixedSize(340,height);
         }
    });

    // connect(this, &T_CaseInformation::signaleditEnable,this,&ExpandableCard::editEnable);
    // connect(this, &T_CaseInformation::signaleditDisable,this,&ExpandableCard::editDisable);
}
T_CaseInformation::~T_CaseInformation()
{}


//Qlineeit是text()和setText()
void T_CaseInformation::datestartEditing()
{
    dateEdit->setText(dateTag->text());
    dateEdit->show();
    dateTag->hide();
    dateEdit->setFocus();
}

void T_CaseInformation::diagnosisstartEditing()
{
    diagnosisEdit->setText(diagnosisTag->text());
    diagnosisEdit->show();
    diagnosisTag->hide();
    diagnosisEdit->setFocus();

}

void T_CaseInformation::complaintstartEditing()
{
    complaintEdit->setText(complaintTag->text());
    complaintEdit->show();
    complaintTag->hide();
    complaintEdit->setFocus();
}

void T_CaseInformation::bodycheckstartEditing()
{
    bodycheckEdit->setText(bodycheckTag->text());
    bodycheckEdit->show();
    bodycheckTag->hide();
    bodycheckEdit->setFocus();
}

void T_CaseInformation::presenthistorystartEditing()
{
    presenthistoryEdit->setText(presenthistoryTag->text());
    presenthistoryEdit->show();
    presenthistoryTag->hide();
    presenthistoryEdit->setFocus();
}

void T_CaseInformation::anamnesisstartEditing()
{
    anamnesisEdit->setText(anamnesisTag->text());
    anamnesisEdit->show();
    anamnesisTag->hide();
    anamnesisEdit->setFocus();
}


void T_CaseInformation::datefinishEditing()
{
    dateTag->setText(dateEdit->text());
    dateTag->show();
    dateEdit->hide();
}

void T_CaseInformation::diagnosisfinishEditing()
{
    diagnosisTag->setText(diagnosisEdit->text());
    diagnosisTag->show();
    diagnosisEdit->hide();
}

void T_CaseInformation::bodycheckfinishEditing()
{
    bodycheckTag->setText(bodycheckEdit->text());
    bodycheckTag->show();
    bodycheckEdit->hide();
}

void T_CaseInformation:: complaintfinishEditing()
{
    complaintTag->setText(complaintEdit->text());
    complaintTag->show();
    complaintEdit->hide();
}

void T_CaseInformation::presenthistoryfinishEditing()
{

    presenthistoryTag->setText(presenthistoryEdit->text());
    presenthistoryTag->show();
    presenthistoryEdit->hide();
}

void T_CaseInformation::anamnesisfinishEditing()
{

    anamnesisTag->setText(anamnesisEdit->text());
    anamnesisTag->show();
    anamnesisEdit->hide();

}


void T_CaseInformation::onImportClicked() {
    QString openPath = QFileDialog::getOpenFileName(
        this,
        "选择病历文件",
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
        "文本文件 (*.txt)"
    );

    if (openPath.isEmpty()) return;

    QFile file(openPath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        ElaMessageBar::error(ElaMessageBarType::Top, "错误", "文件打开失败!", 2000);
        return;
    }

    QTextStream in(&file);
    QString content = in.readAll();
    file.close();

    // 解析文件内容
    QRegularExpression re(
        // 基本信息
        "\\*{20}\\[基本信息\\]\\*{20}\\n+"
        "姓名:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)"  // 姓名
        "\\n+编号:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)" // 编号
        "\\n+入院日期:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)" // 日期

        // 诊断信息
        "\\*{20}\\[诊断信息\\]\\*{20}\\n+"
        "入院诊断:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)"
        "\\n+查体结果:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)"

        // 病史记录
        "\\*{20}\\[病史记录\\]\\*{20}\\n+"
        "主诉:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)"
        "\\n+现病史:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)"
        "\\n+既往史:\\n+(.*?)(?=\\n+\\S+|\\*{20}|\\Z)"

        // 时间轴（关键修改）
        "\\*{20}\\[时间轴记录\\]\\*{20}\\n+"
        "(.*)"  // 捕获全部剩余内容

        "\\Z",  // 匹配到文件结尾
        QRegularExpression::DotMatchesEverythingOption |
        QRegularExpression::MultilineOption
    );

    QRegularExpressionMatch match = re.match(content);
    if (!match.hasMatch()) {
        ElaMessageBar::error(ElaMessageBarType::Top, "错误", "文件格式不正确!", 2000);
        return;
    }

    // 获取匹配数据
    _name = match.captured(1).trimmed();
    _Id = match.captured(2).trimmed();
    _date = match.captured(3).trimmed();
    _diagnosis = match.captured(4).trimmed();
    _bodycheck = match.captured(5).trimmed();
    _complaint = match.captured(6).trimmed();
    _presenthistory = match.captured(7).trimmed();
    _anamnesis = match.captured(8).trimmed();

    // 解析时间轴
    QString timelineContent = match.captured(9);
    QRegularExpression timelineRe("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})\\n(.*?)(\\n\\n|$)");
    QRegularExpressionMatchIterator i = timelineRe.globalMatch(timelineContent);

    _timeVec.clear();
    _contentVec.clear();
    while (i.hasNext()) {
        QRegularExpressionMatch tMatch = i.next();
        _timeVec.append(tMatch.captured(1));
        _contentVec.append(tMatch.captured(2));
    }

    // 创建本地存储文件
    createLocalFiles();

    // 刷新界面显示
    //refreshUI();
    ElaMessageBar::success(ElaMessageBarType::Top, "提示", "病历导入成功!", 1500);
}

void T_CaseInformation::createLocalFiles() {
    // 创建patient文件
    QString patientPath = QString("resource/patients/patient/%1.txt").arg(_name);
    QDir().mkpath(QFileInfo(patientPath).absolutePath());

    QFile pFile(patientPath);
    if (pFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&pFile);
        out << "[name]\n" << _name << "\n"
            << "[Id]\n" << _Id << "\n";
        pFile.close();
    }

    // 创建document文件
    QString docPath = QString("resource/patients/document/%1_%2.txt").arg(_name).arg(_Id);
    QFile dFile(docPath);
    if (dFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&dFile);

        // 手动拼接时间轴
        QString timeStr;
        for (int i = 0; i < _timeVec.size(); ++i) {
            timeStr += _timeVec[i];
            if (i < _timeVec.size() - 1) timeStr += "\n";
        }

        // 手动拼接内容
        QString contentStr;
        for (int i = 0; i < _contentVec.size(); ++i) {
            contentStr += _contentVec[i];
            if (i < _contentVec.size() - 1) contentStr += "\n";
        }

        out << "[gender]\n\n"
            << "[age]\n\n"
            << "[zone]\n\n"
            << "[date]\n" << _date << "\n"
            << "[diagnosis]\n" << _diagnosis << "\n"
            << "[bodycheck]\n" << _bodycheck << "\n"
            << "[complaint]\n" << _complaint << "\n"
            << "[presenthistory]\n" << _presenthistory << "\n"
            << "[anamnesis]\n" << _anamnesis << "\n"
            << "[time]\n" << timeStr << "\n"
            << "[manner]\n" << contentStr << "\n";
        dFile.close();
    }
}

//void T_CaseInformation::refreshUI() {
//    // 更新所有界面控件显示
//    name->setText("姓名:" + _name);
//    Id->setText("患者ID:" + _Id);
//    dateTag->setText("入院日期:" + _date);
//    diagnosisTag->setText("入院诊断:" + _diagnosis);
//    bodycheckTag->setText("入院查体:" + _bodycheck);
//    complaintTag->setText("主诉:" + _complaint);
//    presenthistoryTag->setText("现病史:" + _presenthistory);
//    anamnesisTag->setText("既往史:" + _anamnesis);
//
//    // 刷新时间轴卡片
//    if (!cardVector.isEmpty()) {
//        qDeleteAll(cardVector);
//        cardVector.clear();
//    }
//
//    for (int i = 0; i < _timeVec.size(); i++) {
//        ExpandableCard* card = new ExpandableCard(_timeVec[i], "", _contentVec[i], this);
//        cardVector.append(card);
//        cardLayout->insertWidget(i, card);
//    }
//    cardNumber = _timeVec.size();
//}


// 实现保存功能
void T_CaseInformation::onSaveClicked() {
    // 生成默认文件名
    QString defaultName = QString("%1_%2").arg(_name).arg(_Id);

    // 弹窗选择保存路径
    QString savePath = QFileDialog::getSaveFileName(
        this,
        "保存病历文件",
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/" + defaultName,
        "文本文件 (*.txt)"
    );

    if (savePath.isEmpty()) return;

    // 打开文件
    QFile file(savePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        ElaMessageBar::error(ElaMessageBarType::Top, "错误", "文件保存失败!", 2000);
        return;
    }

    // 构建格式化内容
    QString content;
    content += QString("********************");
    content += QString("[基本信息]");
    content += QString("********************");
    content += QString("\n");
    content += QString("姓名:\n%1\n\n").arg(_name);
    content += QString("编号:\n%1\n\n").arg(_Id);
    content += QString("入院日期:\n%1\n\n\n").arg(_date);

    content += QString("********************");
    content += QString("[诊断信息]");
    content += QString("********************");
    content += QString("\n");
    content += QString("入院诊断:\n%1\n\n").arg(_diagnosis);
    content += QString("查体结果:\n%1\n\n\n").arg(_bodycheck);

    content += QString("********************");
    content += QString("[病史记录]");
    content += QString("********************");
    content += QString("\n");
    content += QString("主诉:\n%1\n\n").arg(_complaint);
    content += QString("现病史:\n%1\n\n").arg(_presenthistory);
    content += QString("既往史:\n%1\n\n\n").arg(_anamnesis);

    content += QString("********************");
    content += QString("[时间轴记录]");
    content += QString("********************");
    content += QString("\n");
    for (int i = 0; i < _timeVec.size(); ++i) {
        content += QString("%1\n%2\n\n").arg(_timeVec[i]).arg(_contentVec[i]);
    }

    // 写入文件
    QTextStream out(&file);
    //out.setCodec("UTF-8");
    out << content;
    file.close();

    ElaMessageBar::success(ElaMessageBarType::Top, "提示", "病历保存成功!", 1500);
}
